package com.dayuanit.dy17.atm.filter;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy17.atm.config.AtmPropertiesConfig;
import com.dayuanit.dy17.atm.dto.ResponseDTO;
import com.dayuanit.dy17.atm.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * URL地址分为：受保护的和不受保护的
 * 受保护的URL：必须登录后才能访问。
 * 不受保护的地址：游客也能访问
 */
public class LoginFilter implements Filter {

    //白名单URL地址集合
    private List<String> whiteUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //读取Filter初始化参数
        String whilteFileName = filterConfig.getInitParameter("whilteFileName");
        InputStream resourceAsStream = LoginFilter.class.getClassLoader().getResourceAsStream(whilteFileName);
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            String whiteUrlMsg = properties.getProperty("white.urls");

            System.out.println("--------LoginFilter init()-------whiteURLs=" + whiteUrlMsg);
            String[] urls = whiteUrlMsg.split(",");
            whiteUrls = new ArrayList<>(urls.length);

            //将数组元素存放到List集合  普通程序员
//            for (String u : urls) {
//                whiteUrls.add(u);
//            }

            //数组转集合  优秀程序员  通过Arrays工具类asList方法转集合
            List<String> strings = Arrays.asList(urls);

            //思考：如何将arrayList集合转数组？  面试题

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        //当前请求的URL地址
        String requestURI = httpServletRequest.getRequestURI();
        System.out.println(">>>>>>>>requestURI=" + requestURI);

        //若地址存在于白名单里，则地址是不受保护的，直接放行
        if (whiteUrls.contains(requestURI)) {
            chain.doFilter(request, response);//将请求传递给下一个Filter
            return;
        }

        //受保护的地址
        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("loginUser");
        if (null == user) {
            String ajaxFlag = httpServletRequest.getHeader("X-Requested-With");

            //同步
            if (StringUtils.isBlank(ajaxFlag)) {
//                httpServletRequest.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(httpServletRequest, httpServletResponse);
                httpServletResponse.sendRedirect("/user/toLogin.do");
                return;
            } else {
                //异步
                httpServletResponse.setContentType("application/json;charset=utf-8");//设置响应头 告诉客户端 返回的内容以及编码集
                httpServletResponse.getOutputStream().write(JSON.toJSONString(ResponseDTO.reLogin()).getBytes("utf-8"));
                return;
            }
        }

        //如果已经登录，则放行。
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("----------LoginFilter destroy()------------");
    }
}
